//
//  APHomeViewController.m
//  TestPrj
//
//  Created by 朱铅峰 on 2020/5/6.
//  Copyright © 2020 Xing. All rights reserved.
//

#import "APHomeViewController.h"
#import "APViewModel.h"
#import "APHomeNavBarView.h"
#import "APHomeTableView.h"
#import <MJRefresh.h>
#import "APHomeHeaderView.h"

@interface APHomeViewController ()

proStrong APHomeNavBarView *navBarView;
proStrong APHomeTableView *tableView;

@end

@implementation APHomeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.barTintColor = [APViewModel themeColor];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:self.navBarView];
    self.navigationItem.leftBarButtonItem = item;
    
    // 设定tableView的行数
    self.tableView.rowCount = 20;
    
    __weak __typeof(self)weakSelf = self;
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadMoreData];
    }];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, kNavBarHeight, 0);
    self.tableView.mj_header.ignoredScrollViewContentInsetTop = -[APHomeHeaderView viewHeight];
    self.tableView.contentOffsetAction = ^(CGFloat contentOffsetY) {
        weakSelf.navBarView.hidden = contentOffsetY < 50;
        if (contentOffsetY > 100) {
            weakSelf.navBarView.alpha = 1;
        } else if (contentOffsetY > 50) {
            weakSelf.navBarView.alpha = 1 - (100 - contentOffsetY) / 50.f;
        }
    };
}

#pragma mark - data

- (void)loadMoreData {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
    });
}

#pragma mark - getter and setter

- (APHomeNavBarView *)navBarView {
    
    if (!_navBarView) {
        _navBarView = [[APHomeNavBarView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, [APHomeNavBarView viewHeight])];
        _navBarView.hidden = YES;
    }
    return _navBarView;
}

- (APHomeTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[APHomeTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStylePlain];
        [self.view addSubview:_tableView];
    }
    
    return _tableView;
}

@end
